package de.webtech.faceplace.pages;

import java.util.Date;
import java.util.List;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import de.webtech.faceplace.entities.Person;



public class Welcome {

	@Property
	@Persist
	private String email;
	@Property
	@Persist
    private String password;
	

	
	@Inject
	Request request;
	
    private List<Person> persons;
	
    @Component(id = "password")
    private PasswordField passwordField;
    
    @Inject
    private Session session;

    @Component
    private Form loginForm;

    
    void onValidateFromLoginForm()
    {
    if(isValid(email, password))
       
    	{
    		onSuccess();
    		
        }
    else{
    	loginForm.recordError(passwordField, "Invalid user name or password.");
    }
    }
    
    public boolean isValid(String email, String password){
    	persons = session.createCriteria(Person.class).list();
		
		for(Person p:persons)	{
			if(p.email.equals(email))	{
				if(p.password.equals(password)){
					request.getSession(true).setAttribute("user",p);
					return true;
				
				}else
					return false;
			}
		}
		return false;
	}
    
    Object onSuccess()
    {
    	
        return "index";
    	
    }
    public Date getCurrentTime()
    {
        return new Date();
    }
	
	
}
